package com.wang.web3;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wang.web3.adapter.KittyGrilAdapter;
import com.wang.web3.base.Constant;
import com.wang.web3.bean.ContractBean;
import com.wang.web3.bean.GirlBean;
import com.wang.web3.bean.TianWallet;
import com.wang.web3.contracts.GirlCore;
import com.wang.web3.data.service.ICallBackListener;
import com.wang.web3.data.service.impl.ApiServiceImpl;
import com.wang.web3.utils.SPUtils;

import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tuples.generated.Tuple6;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import rx.functions.Action1;

public class GirlStrongActivity extends AppCompatActivity implements KittyGrilAdapter.PersonHolderListener, View.OnClickListener {

    Gson gson = new Gson();
    List<GirlBean.DataBean> girlLists, girlLists2;
    KittyGrilAdapter kittyGrilAdapter, kittyGrilAdapter2;
    RecyclerView mRv1, mRv2;
    ImageView mIvGirl;
    TextView mTvGirl;
    Button mBtn;
    int selectid;
    List<Integer> xiaohaoList = new ArrayList<Integer>();
    List<BigInteger> bigIntegerList = new ArrayList<>();

    ContractBean contractBean;
    Credentials credentials;
    GirlCore girlCore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_girl_strong);
        findViewById(R.id.mLeftIv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRv1 = findViewById(R.id.mRv1);
        mRv2 = findViewById(R.id.mRv2);
        mIvGirl = findViewById(R.id.iv_girl);
        mTvGirl = findViewById(R.id.tv_girl);
        mBtn = findViewById(R.id.mBtn);
        mBtn.setOnClickListener(this);

        init();
        initData();
    }

    private void init() {
        girlLists = new ArrayList<>();
        kittyGrilAdapter = new KittyGrilAdapter(girlLists, this);
        mRv1.setLayoutManager(new LinearLayoutManager(this));
        mRv1.setAdapter(kittyGrilAdapter);

        girlLists2 = new ArrayList<>();
        kittyGrilAdapter2 = new KittyGrilAdapter(girlLists2, personHolderListener);
        mRv2.setLayoutManager(new LinearLayoutManager(this));
        mRv2.setAdapter(kittyGrilAdapter2);

        Web3j web3 = Web3jFactory.build(new HttpService(Constant.URL));
        String wallet = (String) SPUtils.get(this, Constant.WALLETLOCKADDRESS, "");
        String contract = (String) SPUtils.get(this, Constant.CONTRACTADDRESS, "");
        TianWallet tianWallet = gson.fromJson(wallet, TianWallet.class);
        contractBean = gson.fromJson(contract, ContractBean.class);
        credentials = Credentials.create(tianWallet.getPrivateKey().substring(2));
        if (contractBean != null && contractBean.getMagicKeys() != null) {
            girlCore = GirlCore.load(contractBean.getGirlCore(), web3, credentials, Constant.GAS_PRICE, Constant.GAS_LIMIT);
        }
//        GirlCore girlCore =

    }

    private void initData() {
        String lockWallet = (String) SPUtils.get(this, Constant.WALLETLOCKADDRESS, "");
        if (lockWallet.equals("")) {
            return;
        }
        TianWallet tianWallet = gson.fromJson(lockWallet, TianWallet.class);
        ApiServiceImpl.getInstence().myGirlList(tianWallet.getAdress(), new ICallBackListener() {
            @Override
            public void onSuccess(String string) {
                GirlBean girlBean = gson.fromJson(string, GirlBean.class);
                girlLists.addAll(girlBean.getData());
                kittyGrilAdapter.notifyDataSetChanged();

                girlLists2.addAll(girlBean.getData());
                kittyGrilAdapter2.notifyDataSetChanged();

            }

            @Override
            public void onFaild(String string) {

            }
        });

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                Toast.makeText(GirlStrongActivity.this, "强化成功", Toast.LENGTH_SHORT).show();
                initData();
            }
            return false;
        }
    });

    public void tobestrong() {
        try {
            final RemoteCall<TransactionReceipt> rm = girlCore.triggerStreng(new BigInteger("" + selectid), bigIntegerList);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        rm.observable().subscribe(new Action1<Object>() {
                            @Override
                            public void call(Object o) {
                                TransactionReceipt ss = (TransactionReceipt) o;
                                List<GirlCore.StrengEventResponse> list = girlCore.getStrengEvents(ss);
                                Log.e("Tag", list.size() + "---");
                                Message message = Message.obtain();
                                message.what = 1;
                                handler.sendMessage(message);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGirlPersonItemClicked(View v, MotionEvent event, int position) {
        try {
            Tuple6<BigInteger, BigInteger, BigInteger, BigInteger, Boolean, BigInteger> tuple6 = girlCore.getGirl(new BigInteger(girlLists.get(position).getId() + "")).sendAsync().get();
            Glide.with(this).load(girlLists.get(position).getPicBody()).into(mIvGirl);
            selectid = girlLists.get(position).getId();
            kittyGrilAdapter.notifyDataSetChanged();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {

        }
    }

    KittyGrilAdapter.PersonHolderListener personHolderListener = new KittyGrilAdapter.PersonHolderListener() {
        @Override
        public void onGirlPersonItemClicked(View v, MotionEvent event, int position) {

            if (girlLists2.get(position).getId() == selectid) {
                Toast.makeText(GirlStrongActivity.this, "不能重复选中", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!girlLists2.get(position).isSelect()) {
                girlLists2.get(position).setSelect(true);
                xiaohaoList.add(girlLists2.get(position).getId());
            } else {
                girlLists2.get(position).setSelect(false);
                xiaohaoList.remove(xiaohaoList.indexOf(girlLists2.get(position).getId()));
            }
            kittyGrilAdapter2.notifyDataSetChanged();
            getSuccessRate();
        }
    };

    private void getSuccessRate() {

        bigIntegerList = new ArrayList<>();
        for (int i = 0; i < xiaohaoList.size(); i++) {
            bigIntegerList.add(new BigInteger("" + xiaohaoList.get(i)));
        }
        try {
            BigInteger bigInteger = girlCore.getSuccessRate(new BigInteger("" + selectid), bigIntegerList).sendAsync().get();
            mTvGirl.setText("强化成功率：" + bigInteger + "%");
            Log.e("Tag", "---" + bigInteger);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.mBtn) {
            tobestrong();
        }
    }

}
